//
//  ZqlcomposeVC.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/26.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class ZqlcomposeVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.orangeColor()
        
        setNavBar()
        setTextView()
        setBottomToolBar()
        registNotification()
    }
    
    //注册通知
    private func registNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardDidChangeFrameNotification, object: nil)
    }
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //实现通知方法
    @objc private func keyBoardWillChange(nf:NSNotification){
        //获取动画运行时间
        let duration = (nf.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let rect = (nf.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let height = -ScreenHeight + rect.origin.y
        //添加动画
        UIView.animateWithDuration(duration) { () -> Void in
          self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
            
            make.bottom.equalTo(height)

          })
            //强制刷新界面
            self.view.layoutIfNeeded()
        }
    }
    
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    //添加底部工具条
    private func setBottomToolBar(){
        
       view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
        }
        
        var items = [UIBarButtonItem]()
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_add_background"]]
        for item in itemSettings{
            let imageName = item["imageName"]
            let btn = UIButton(backImageName: nil, imageName: imageName)
            let barItem = UIBarButtonItem(customView: btn)
            //将自定义的按钮添加到UIBarButtonItem数组中
            items.append(barItem)
            //添加弹簧按钮
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //移除最后一个按钮
        items.removeLast()
        //设置按钮的个数
        toolBar.items = items
    }

    //实现按钮的点击事件
    @objc private func clickClose(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func clickSend(){
        let urlString = "2/statuses/update.json"
        let parameters = ["access_token":ZqlAccountVM.shardAccountVM.access_token,"status":textView.text]
        ZqlHTTPClient.sharedClient.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发布微博失败,请检查网络")
                return
            }
            //发布成功则关闭当前页面
            self.clickClose()
        }
    }

  //设置导航条
    private func setNavBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "clickClose")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "clickSend")
        
        //开始时发送按钮禁止点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        let weiboTitle:UILabel = UILabel(text: "发布微博", fontSize: 18, textColor: UIColor.darkGrayColor())
        let nameLable:UILabel = UILabel(text: ZqlAccountVM.shardAccountVM.userName ?? "", fontSize: 14, textColor: UIColor.lightGrayColor())
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        navigationItem.titleView?.addSubview(weiboTitle)
        navigationItem.titleView?.addSubview(nameLable)
        
        //设置约束
        weiboTitle.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        nameLable.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
    }
    
    //设置文本框
    private func setTextView(){
        //添加 子视图
        view.addSubview(textView)
        //设置约束 约束完一个控件就立即查看布局效果
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.view.snp_top)
            make.left.equalTo(self.view.snp_left)
            make.right.equalTo(self.view.snp_right)
            make.height.equalTo(ScreenHeight / 3)
        }
        //添加占位文本
        textView.addSubview(placeHolder)
        //设置占位文本的约束
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    //懒加载
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.lightGrayColor()
        tv.backgroundColor = UIColor.greenColor()
        //设置textview垂直方向可以滚动
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        //设置代理
        tv.delegate = self
        return tv
    }()
    
    //懒加载文本占位符
    private lazy var placeHolder: UILabel = UILabel(text: "输入新鲜事...", fontSize: 18, textColor: UIColor(white: 0.7, alpha: 1))

}

//实现textview的代理方法
extension ZqlcomposeVC:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        placeHolder.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}









